/**
 * Get the value of a CSS custom property.
 *
 * @param {string} cssVariableName - The name of the CSS custom property.
 * @returns {string} The value of the CSS custom property.
 */
export const getCssVariableValue = cssVariableName => {
  let cssVariableValue = ''
  try {
    cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
  } catch (error) {
    console.error(error)
  }
  return cssVariableValue
}

/**
 * Set the value of a CSS custom property.
 *
 * @param {string} cssVariableName - The name of the CSS custom property.
 * @param {string} cssVariableValue - The value to set for the CSS custom property.
 */
export const setCssVariableValue = (cssVariableName, cssVariableValue) => {
  try {
    // Set the value of the CSS custom property.
    document.documentElement.style.setProperty(cssVariableName, cssVariableValue)
  } catch (error) {
    // Log any errors that occur.
    console.error(error)
  }
}


export const storage = (key, value, expires) => {
  if (!key) return

  const now = Math.floor(Date.now() / 1000)
  const del = () => window.localStorage.removeItem(key)
  const read = attr => {
    try {
      const store = JSON.parse(window.localStorage.getItem(key)) || {}
      if (store.expires && store.expires <= now) return del()
      return store[attr]
    } catch {
      return null
    }
  }
  const write = () => {
    const expiresTime = read('expires')
    const data = { value }
    if (+expires) data.expires = now + Math.floor(+expires)
    else if (expiresTime) data.expires = expiresTime
    window.localStorage.setItem(key, JSON.stringify(data))
  }

  if (typeof value === 'undefined') return read('value')
  if (value === null && expires === true) return read('expires')
  if (value === null || expires < 0) return del()
  write()
}